package {
	import com.ecity.events.GameEvent;
	import com.ecity.events.GameState;
	import com.ecity.util.GridEngine;
	import com.ecity.util.Samulator;
	import com.ecity.util.UIFactory;
	import com.ecity.view.Viewer;
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.SpreadMethod;
	import flash.display.Sprite;
	import flash.events.MouseEvent;
	import flash.external.ExternalInterface;
	import flash.text.TextField;
	
	/**
	 * ...
	 * @author yicheng.zhang
	 */
	public class Main extends Sprite {
		private var viewer:Viewer;
		private var engine:GridEngine;
		private var layer:Sprite = new Sprite();
		private var samulator:Samulator = new Samulator();
	
		public function Main():void {
			viewer = new Viewer();
			engine = new GridEngine();
			layer.addChild(samulator);//===========================
			this.addChild(viewer);
			this.addChild(layer);
			samulator.addEventListener(GameEvent.SAMULATOR_CLICK, onSamulatorClick);
			engine.addEventListener(GameEvent.REQ_GAME_START, reqGameStart);
			initCaller();
		}
		
		private function reqGameStart(e:GameEvent):void {
			var nnn:Bitmap = UIFactory.getBitmapbyName("initpage") as Bitmap;
			var bmd:BitmapData = nnn.bitmapData.clone();
			this.addChildAt(new Bitmap(bmd),0);
			viewer.startGame();
		}
		
		private function onSamulatorClick(e:GameEvent):void {
			engine.judge(e._info.mx, e._info.my);
			viewer.hitTestCase(e._info.mx, e._info.my);
			
		}
		
		private function initCaller():void {
			try {
				ExternalInterface.addCallback("iCall", iCall);
			} catch (error:SecurityError) {
			} catch (error:Error) {
			}
		}

		public function iCall(param: String):String {
			var p:Array = param.split('|');
			var pos:Array;
			var tx:int;
			var ty:int;
			for (var i:int = 0; i < p.length; i ++){
				pos = p[i].split(',');
				tx = pos[0];
				ty = pos[1];
				engine.judge(tx, ty);
				viewer.hitTestCase(tx, ty);
				samulator.drawRects(tx, ty);
			}
			return "";
		}
		
	}
}